<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    #modal {
      position: fixed;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      width: 200px;
      height: 200px;
      background-color: #dcdddf;
    }
  </style>
</head>

<body>
  <p>单例模式面试题</p>
  <button id="btn1">开启Modal</button>
  <button id="btn2">关闭Modal</button>
  <script src="./单例模式面试题.js"></script>
  <script>
    /**
     * 2. 实现一个全局唯一的Modal弹框
     */
    class Modal {
      constructor() {
        this.modal = document.createElement('div')
        this.modal.innerHTML = '单例模式全局Modal'
        this.modal.id = 'modal'
        this.modal.style.display = 'nonoe'
        document.body.appendChild(this.modal)
      }

      static getInstance() {
        if (!Modal.instance) {
          Modal.instance = new Modal()
        }
        return Modal.instance
      }

      open() {
        this.modal.style.display = 'block'
      }
      close() {
        this.modal.style.display = 'none'
      }
    }

    document.getElementById('btn1').addEventListener('click', () => {
      const modal = Modal.getInstance()
      modal.open()
    })
    document.getElementById('btn2').addEventListener('click', () => {
      const modal = Modal.getInstance()
      modal.close()
    })
  </script>
</body>

</html>